package com.mawc.equipower.soket;

/**
 * @Author: zhouhe
 * @Date: 2019/4/8 9:27
 */

import com.mawc.equipower.enums.Electric;
import com.mawc.equipower.socket2.SocketHandler;
import com.mawc.equipower.utils.HexUtil;
import lombok.val;
import org.junit.Test;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 服务端接收数据
 */
@Component
public class SocketRecieveMsg {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 6665;
    static String login = "40110300000001300400000000000703000000660701000BFF0001FFFFFFFFFFFF0101C823";
    static String dataPacket = "40 11 03 00 00 00 02 30 04 00 00 00 00 00 07 03 00 00 00 66 07 29 02 16 00 00 00 FF FF FF FF FF FF 04 00 00 00 01 01 00 00 FF FF FF FF FF FF 04 00 00 00 00 02 00 00 FF FF FF FF FF FF 04 00 00 00 01 03 00 00 FF FF FF FF FF FF 04 00 00 00 00 04 00 00 FF FF FF FF FF FF 04 00 00 00 00 05 00 00 FF FF FF FF FF FF 04 00 00 00 00 06 00 00 FF FF FF FF FF FF 04 00 00 00 00 07 00 00 FF FF FF FF FF FF 04 00 00 00 00 08 00 00 FF FF FF FF FF FF 04 00 00 00 00 09 00 00 FF FF FF FF FF FF 04 00 00 00 00 0A 00 00 FF FF FF FF FF FF 04 00 00 00 00 0B 00 00 FF FF FF FF FF FF 04 00 00 00 00 0C 00 00 FF FF FF FF FF FF 04 00 00 00 00 0D 00 00 FF FF FF FF FF FF 04 00 00 00 00 0E 00 00 FF FF FF FF FF FF 04 00 00 00 00 0F 00 02 FF FF FF FF FF FF 02 00 00 10 00 02 FF FF FF FF FF FF 02 00 00 11 00 02 FF FF FF FF FF FF 02 00 00 12 00 02 FF FF FF FF FF FF 02 00 00 13 00 02 FF FF FF FF FF FF 02 02 BF 14 00 02 FF FF FF FF FF FF 02 02 C5 15 00 02 FF FF FF FF FF FF 02 02 BE 16 00 02 FF FF FF FF FF FF 02 02 BC 17 00 02 FF FF FF FF FF FF 02 09 2C 18 00 02 FF FF FF FF FF FF 02 09 35 19 00 02 FF FF FF FF FF FF 02 09 20 1A 00 02 FF FF FF FF FF FF 02 00 00 1B 00 02 FF FF FF FF FF FF 02 00 00 1C 00 02 FF FF FF FF FF FF 02 00 00 1D 00 03 FF FF FF FF FF FF 04 00 00 00 00 1E 00 03 FF FF FF FF FF FF 04 00 00 00 00 1F 00 03 FF FF FF FF FF FF 04 00 00 00 00 20 00 02 FF FF FF FF FF FF 02 00 00 21 00 02 FF FF FF FF FF FF 02 00 00 22 00 02 FF FF FF FF FF FF 02 00 00 23 00 02 FF FF FF FF FF FF 02 01 F4 24 00 02 FF FF FF FF FF FF 02 01 F4 25 00 02 FF FF FF FF FF FF 02 01 F4 26 00 04 FF FF FF FF FF FF 04 00 00 00 0A 27 00 04 FF FF FF FF FF FF 04 00 00 00 0A 28 00 04 FF FF FF FF FF FF 04 00 00 00 0A A2 23";
    static String jump = "40 11 03 00 00 00 03 30 04 00 00 00 00 00 07 03 00 00 00 66 07 01 00 0B FE 00 01 FF FF FF FF FF FF 01 02 CA 23";


    static String rev1 = "40 11 04 00 00 00 01 01 00 17 23";
    static String rev2 = "40 11 04 00 00 00 02 01 00 18 23";
    static String rev3 = "40 11 04 00 00 00 03 01 00 19 23";

    static String datapath = "f:/newfile/newfile.txt";
    private static File fileTxt = new File(datapath);
    private static FileOutputStream fop;
    {
        try {
            fop = new FileOutputStream(fileTxt);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void recieMsg() throws IOException {

        boolean flag = false;
        boolean dataFlag = false;
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("服务端已开启...");
        Socket accept = serverSocket.accept();
        System.out.println("服务端已连接到:" + accept.getRemoteSocketAddress());
        Long jumpStartTime;
        Long retryJumpTime = null;
        for (; ; ) {
            InputStream inputStream;
            try {
                inputStream = accept.getInputStream();
                val writerClient = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream(), StandardCharsets.UTF_8));
                DataInputStream dataInputStream = new DataInputStream(inputStream);
                int available = dataInputStream.available();
                if (available != 0) {
                    if (!flag) {
                    }
                    byte b[] = new byte[available];
                    dataInputStream.read(b);
                    if (b.length != 0) {
                        String s = HexUtil.bytesToHex(b);
                        DataOutputStream dataOutputStream = new DataOutputStream(accept.getOutputStream());
                        if (s.equals(trimStr(login)) || flag) {
                            if (!flag) {
                                System.out.println("设备登陆成功发送登录包:" + s);
                                flag = true;
                                writeHexStr(trimStr(rev1), writerClient);
                                System.out.println("服务端回复登录包:" + rev1);
                                continue;
                            }

//                                if (s.length() > 1000) {
//
//                                if (s.substring(0,1115) == dataPacket){
//                                    System.out.println("设备发送数据包:" + s);
//                                    writeHexStr(trimStr(rev2), writerClient);
//                                    System.out.println("服务端回复数据包:" + rev2);
//                                    dataFlag = true;
//                                    continue;
//                                }
//                                }
                            if (s.equals(trimStr(dataPacket)) || !dataFlag) {
                                System.out.println("设备发送数据包:" + s);
                                writeHexStr(trimStr(rev2), writerClient);
                                System.out.println("服务端回复数据包:" + rev2);
                                dataFlag = true;
                                continue;
                            }
                            if (s.equals(trimStr(jump))) {
                                System.out.println("设备发送心跳包:" + s);
                                writeHexStr(trimStr(rev3), writerClient);
                                System.out.println("服务端回复心跳包:" + rev3);
//                                jumpStartTime=System.currentTimeMillis();
//                                retryJumpTime=jumpStartTime+6*1000;
                                continue;
                            }
                            /*else {
                                System.out.println("Device package: " + s);
                                writeTxt(s);
                                //fileOutputStream.write(s.getBytes());
                                //fileWriter.append(trimStr(s));
                                dataOutputStream.writeUTF(rev3);
                                dataOutputStream.flush();
                                // fileOutputStream.flush();
                                // fileOutputStream.close();
                                //FileUtil.appendString(s,txtPath,"utf-8");
                            }*/
                        } else {
//                            System.out.println("设备数据包: " + s);
//                            //writeTxt(s);
//                            //fileOutputStream.write(s.getBytes());
//                            //fileWriter.append(trimStr(s));
////                            dataOutputStream.writeUTF("The login data is incorrect, please re-enter it!");
//                            dataOutputStream.flush();
//                            // fileOutputStream.flush();
//                            // fileOutputStream.close();
//                            //FileUtil.appendString(s,txtPath,"utf-8");
                        }

                    }
                }
            } catch (IOException e) {
                try {
                    e.printStackTrace();
                    accept.close();
                } catch (IOException exception) {
                    System.out.println("client disconnected");
                }
            }

        }

    }

    public static void writeTxt(String s) throws IOException {
        // if file doesn't exists, then create it
        if (!fileTxt.exists()) {
            fileTxt.createNewFile();
        }
        fop.write(s.getBytes());
        fop.write("\n".getBytes());
        System.out.println("The contents written to the txt file are: " + s);
    }

   /* private void recieMsg() throws IOException {
        ServerSocket socket = new ServerSocket(PORT);
        System.out.println("server is running...");

        Socket accept = socket.accept();
        System.out.println("connect from" + accept.getRemoteSocketAddress());
        for (;;){
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
            handle(accept);
        }

    }*/

    /*private static void handle(Socket socket) {
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            try (OutputStream output = socket.getOutputStream()) {
                DataInputStream reader = new DataInputStream(inputStream);


                int available = reader.available();

                if (available != 0) {
                    byte b[] = new byte[available];
                    int receive = reader.read(b);
                    if (login.equals(receive)) {
                        System.out.println("设备登录：" + login);
                        writer.write(rev1);
                        writer.flush();
                    }
                    if (s.equals("bye")) {
                        writer.write("bye\n");
                        writer.flush();
                        writer.close();
                    }
                }


            }

        } catch (Exception e) {
            try {
                socket.close();
            } catch (IOException ioe) {
            }
            System.out.println("client disconnected.");
        }
    }*/

    public String trimStr(String s) {
        return s.replaceAll(" ", "").toUpperCase();
    }

    public String writeHexStr(String s, Writer output) throws IOException {
        String hexStr = "";
        int count = 0;
        for (int i = 0; i < s.length() / 2; i++) {
            long l = Long.parseLong(s.substring(count, count + 2), 16);
            //hexStr+=s.substring(count, count + 2)+" ";
            hexStr += l + " ";
            output.write((int) l);
            output.flush();
            count += 2;
        }
        //System.out.println("The data sent by the service side is: " + hexStr);
        return hexStr;
    }

    @Test
    public void test() throws IOException {
        recieMsg();
    }

    @Test
    public void login() throws IOException {
        writeHexStr("40110300000001300400000000000803000000001401000BFF0001FFFFFFFFFFFF01017023", null);
    }

}